import Vue from 'vue'
import VueRouter from 'vue-router'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import setting from '@/setting'
Vue.use(VueRouter)

// 页面布局
import layoutHeaderAside from '@/layout/index.vue'
// 页面路由 (可通过后端传入的参数动态生成路由)
let pages = [];
const _import = require('@/utils/import.' + process.env.NODE_ENV)
const pagesComponent = require.context('../views', true, /index.vue$/)

pagesComponent.keys().forEach(key => {
  // ./FactoryInfo/index.vue ==> FactoryInfo
  // const page = key.replace(/\/index.vue$/, '').replace(/^\.\//, '')
  const componentConfig = pagesComponent(key)
  const name = componentConfig.default.name
  if (componentConfig.default.meta) {
    pages.push({
      path: `/${name}`,
      name: componentConfig.default.meta.menuId,
      component: _import(key.replace(/^\.\//, '')),
      meta: componentConfig.default.meta
    })
  }
})

const routes = [
  {
    path: '/',
    redirect: { name: 'index' },
    component: layoutHeaderAside,
    children: pages
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('@/layout/system/login')
  },
  {
    path: '*',
    name: '404',
    component: () => import('@/layout/system/error')
  },
]

// 导出路由 在 main.js
const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

/**
 * 路由拦截
 * 权限验证
 */
router.beforeEach(async (to, from, next) => {
  NProgress.start() // 开始进度条
  // 权限验证
  if (localStorage.getItem('token')) {
    if (to.path === '/login') {
      next('/')
    } else {
      next()
    }
  } else {
    if (to.path == '/login') {
      next();
    } else {
      next('/login');
    }
  }
})

router.afterEach(to => {
  NProgress.done() // 开始进度条
  // 更新标题
  document.title = to.meta.title || setting.name
})

export default router
